package com.csp.main.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csp.common.utils.R;
import com.csp.main.config.WebSocketServer;
import com.csp.main.entity.Friends;
import com.csp.main.entity.Message;
import com.csp.main.mapper.MessageMapper;
import com.csp.main.service.FriendsService;
import com.csp.main.service.MessageService;
import com.csp.main.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname MessageController
 * @Description done
 * @Date 2022/6/15 16:13
 * @Created by csp
 */
@RestController
@CrossOrigin
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService service;
    @Autowired
    private FriendsService friendsService;
    @Autowired
    MessageMapper messageMapper;

    @GetMapping("/send/{userId}/{message}")
    public R send(HttpServletRequest request, @PathVariable String userId, @PathVariable String message){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String id = JWTUtils.validateToken(token);
        Map<String,Object> params = new HashMap();
        params.put("sendUserId",id);
        params.put("message",message);
        JSONObject jsonObject = new JSONObject(params);
        String messageJSON = jsonObject.toJSONString();
        Message m = new Message();
        m.setSendId(id);
        m.setReceiveId(userId);
        m.setMessage(message);
        service.save(m);

        try {
            WebSocketServer.sendInfo(messageJSON,userId);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }

    @GetMapping("list/{friendId}/{page}/{limit}")
    public R KindPageArticle(HttpServletRequest request,@PathVariable String friendId,@PathVariable Long page,@PathVariable Long limit){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        Page<Message> pages=new Page<>(page,limit);
        QueryWrapper<Message> queryWrapper=new QueryWrapper<>();
        queryWrapper.and(wrapper1 -> wrapper1.eq("send_id",userId).eq("receive_id",friendId)).or(wrapper2 -> wrapper2.eq("send_id",friendId).eq("receive_id",userId));
        queryWrapper.orderByDesc("gmt_create");
        IPage<Message> iPage = service.page(pages,queryWrapper);
        List<Message> records = iPage.getRecords();
        return R.ok().data("rows",records);
    }

}
